package com.bookpavilion.chat.websocket;

import com.alibaba.fastjson.JSON;
import com.bookpavilion.chat.client.UserClient;
import com.bookpavilion.chat.dao.MessageDao;
import com.bookpavilion.chat.pojo.Message;
import com.bookpavilion.chat.pojo.User;
import com.bookpavilion.chat.service.MessageService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bson.types.ObjectId;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;


public class MessageHandler extends TextWebSocketHandler   {
    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MessageService messageService;
    @Autowired
    private RabbitAdmin rabbitAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private UserClient userClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final Map<String, WebSocketSession> SESSIONS= new HashMap<>();
    private static final List<Map<String,Message>> OFFLINE_MESSAGE_QUERY= new ArrayList<>();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String uid = (String) session.getAttributes().get("uid");
        SESSIONS.put(uid,session);
        if(OFFLINE_MESSAGE_QUERY!=null){
            for (Map<String, Message> map : OFFLINE_MESSAGE_QUERY) {
                Message message = map.get(uid);
                if(message!=null) {
                    messageService.updateMessStatusById(message.getId(), 2);
                    session.sendMessage(new TextMessage(MAPPER.writeValueAsBytes(message)));
                }
            }
        }
    }


//    @Override
//    public void run(String... args) throws Exception {
//        String queueName = SpringUtils.getApplicationContext().getBean(Environment.class).getProperty("queue");//配置文件中配置，也可配置在数据库
//        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(new MessageListen());//消费mq消息的类
//        List<String> queueNamesList = new ArrayList<>();
//        messageListenerAdapter.addQueueOrTagToMethodName(queueName, "getMessage");//消费mq消息的方法
//        queueNamesList.add(queueName);
//        logger.info("新增队列queueName={}", queueName);
//        Queue queue = new Queue(queueName);
//        addQueue(queue);
//        if (!queueNamesList.isEmpty()) {
//            String[] strings = new String[queueNamesList.size()];
//            container.addQueueNames(queueNamesList.toArray(strings));
//        }
//        container.setMessageListener(messageListenerAdapter);
//
//    }


    public void sendMsg(String tenantId,String msg){
        rabbitAdmin.declareQueue(new Queue("bp_chat_message_"+tenantId));
        rabbitTemplate.convertAndSend("bp_chat_message_"+tenantId,msg);
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        String uid = (String) session.getAttributes().get("uid");
        JsonNode jsonNode = MAPPER.readTree(textMessage.getPayload());
        String toId= jsonNode.get("toId").asText();
        LinkedHashMap<String, String> fromData = (LinkedHashMap<String, String>) userClient.findById(uid).getData();
        LinkedHashMap<String, String> toData = (LinkedHashMap<String, String>) userClient.findById(toId).getData();
        User from = User.builder().id(fromData.get("id")).nick_name(fromData.get("nick_name")).head_pic(fromData.get("head_pic")).build();
        User to = User.builder().id(toData.get("id")).nick_name(toData.get("nick_name")).head_pic(toData.get("head_pic")).build();
        String msg = jsonNode.get("msg").asText();
        Message message = Message.builder()
                .from(from)
                .to(to)
                .msg(msg)
                .sendDate(new Date())
                .status(0)
                .build();
        //消息存储到mongo中
        message=messageDao.save(message);
        WebSocketSession toSession = SESSIONS.get(toId);

        /**
         *      判断用户是否在线
         */
        if(toSession!=null&&toSession.isOpen()){
            toSession.sendMessage(new TextMessage(MAPPER.writeValueAsBytes(message)));
            messageService.updateMessStatusById(message.getId(),2);
        }else {
//            Map<String,Message> mess=new HashMap<>();
//            mess.put(toId,message);
//            OFFLINE_MESSAGE_QUERY.add(mess);
            String mes = JSON.toJSONString(message);
            rabbitTemplate.convertAndSend("bp_chat_message",mes);

        }

    }
//    @RabbitHandler
//    public void onMessage(String msg) throws IOException {
//        System.out.println("msg:  "+msg);
////        JsonNode jsonNode = MAPPER.readTree(msg);
////        String toId= jsonNode.get("toId").get("id").asText();
////        WebSocketSession toSession = SESSIONS.get(toId);
////        if(toSession!=null&&toSession.isOpen()){
////            toSession.sendMessage(new TextMessage(msg));
////            messageService.updateMessStatusById(new ObjectId(jsonNode.get("id").asText()),2);
////        }
//    }
}
